package com.google.code.mircle.core.transfers;

import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.swing.JLabel;

/**
 * An extension of JLabel which looks like a link and responds appropriately
 * when clicked. Note that this class will only work with Swing 1.1.1 and later.
 * Note that because of the way this class is implemented, getText() will not
 * return correct values, user <code>getNormalText</code> instead.
 */

public class LinkLabel extends JLabel {

    /**
     * The normal text set by the user.
     */

    private String text;

    /**
     * Creates a new LinkLabel with the given text.
     */

    public LinkLabel(String name) {
        super(name);
        setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        enableEvents(MouseEvent.MOUSE_EVENT_MASK);
    }

    /**
     * Sets the text of the label.
     */

    public void setText(String text) {
        super.setText("<html><font color=\"#0000CF\"><u>" + text + "</u></font></html>"); //$NON-NLS-1$ //$NON-NLS-2$
        this.text = text;
    }

    /**
     * Returns the text set by the user.
     */

    public String getNormalText() {
        return text;
    }

    /**
     * Processes mouse events and responds to clicks.
     */

    protected void processMouseEvent(MouseEvent evt) {
        super.processMouseEvent(evt);
        if (evt.getID() == MouseEvent.MOUSE_CLICKED) {
            Desktop d = Desktop.getDesktop();
            if (d != null) {
                try {
                    d.browse(new URI(getNormalText()));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
